package com.phx.serialjni;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.TouchDelegate;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;

import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

//import com.android.test.PictureDatabase;
import com.phx.uart.uartJni;
import com.phx.uart.uartJnit;
import com.utils.CRC16;
import com.utils.TransformUtils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.Socket;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;

import static com.phx.serialjni.PageS.bitmap;
import static com.phx.serialjni.SQLiteHelper.TB_NAME_IMAGE;

public class MainActivityf extends BaseActivity implements SeekBar.OnSeekBarChangeListener {
    public static String SOCKET_ADDRESS = "com.clzk.mobilej.local";
    private SeekBar seekBar;
    private SeekBar seekBar1;
    private SeekBar seekBar2;
    String headerData = "5aa5";
    byte[] read_buf = new byte[512];
    int fd;
    TextView testView;
    TextView testtView;
    TextView testfView;
    SharedPreferences userInfo;
    MeziView mezi;
    MeziView newm;
    int currentPage = 0;
    PageS pagestatus = new PageS();
    myFrameLayout frame;
    String cmdheader = "5AA50883";
    private static final long TIMER_INTERVAL = 100;
    public int currentPosition = -1;
    private int newPosition = -1;
    private int jmpPostion = -1;
    Handler handler = new Handler();
    private static int POSTION;


    private boolean checkability(String comingdata) {
        boolean result = false;
        try {
            int alllength = comingdata.length() - 3;
            String firstFour = "";
            if ((comingdata.length()) > 4) {
                firstFour = comingdata.substring(0, 4);
                if (firstFour.equals(headerData)) {
                    int msgcounts = Integer.parseInt(comingdata.substring(4, 6), 16);
                    if (alllength == (msgcounts * 2 + 3)) {
                        result = true;
                    }
                }
            }
        } catch (Exception ex) {
            result = false;
        }
        return result;
    }



    SharedPreferences.OnSharedPreferenceChangeListener mListener = new SharedPreferences
            .OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            String msg = sharedPreferences.getString("user_info", "0000");
            Log.e("coming data", "sp token:" + msg);
        }
    };

    void dish(String device, String stat) {
        if (PageS.allDArray[15].equals(device)) {
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2, 3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;
            if ((value > -1) && (value < 101)) {
                if (seekBar != null) {
                    seekBar.setProgress(value);
                }
            }
        }
        if (PageS.allDArray[16].equals(device)) {
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2, 3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;
            if ((value > -1) && (value < 101)) {
                if (seekBar1 != null) {
                    seekBar1.setProgress(value);
                }
            }
        }
        if (PageS.allDArray[17].equals(device)) {
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2, 3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;
            if ((value > -1) && (value < 101)) {
                if (seekBar2 != null) {
                    seekBar2.setProgress(value);
                }
            }
        }
    }
    void disv(String device, String stat) {
        if (PageS.voladdress[0].equals(device)) {
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2, 3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;
            float lastx = (float) 0.0;
            lastx = (float) (value / 10.0);
            NumberFormat formatter = new DecimalFormat("0.0");
            String formmatedFloatValue = formatter.format(lastx) + "V";
            if ((lastx > 0.0) && (lastx < 14.7)) {
                if (testView == null) {
                } else {
                    testView.setText(formmatedFloatValue);
                }
            }
        }
        if (PageS.voladdress[1].equals(device)) {
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2, 3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;
            float lasty = (float) 0.0;
            lasty = (float) (value / 10.0);
            NumberFormat formatter = new DecimalFormat("0.0");
            String formmatedFloatValue = formatter.format(lasty);
            if ((lasty > 0.0) && (lasty < 14.7)) {
                if (testfView == null) {
                } else {
                    testfView.setText(formmatedFloatValue);
                }
            }
        }
    }
    public void slidersend(int seekno, int sseq) {
        String cmdx = PageS.sliderCmd[seekno][sseq];
        String cmdheader = "5AA50883";
        String allCmdx = cmdheader;
        String tmpTmp = cmdx;
        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
        StringBuffer allCmd = CRC16.crc16x(allCmdx);
        final String cmd = allCmd.substring(0, 22);
        new Thread() {
            public void run() {
                super.run();
                try {
                    boolean isSendx = false;
                    isSendx = uartJnit.getInstance().sendCmds(cmd);
                    Log.e("send TAG", "send down: " + cmd);
                    Message msg = new Message();
                    if (isSendx) {
                        Log.e("send TAG", "send down" + cmd + "success");
                    } else {
                        Log.e("TAG", "send down  :" + cmd + "failed!");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    Thread.sleep((long) TIMER_INTERVAL);
                } catch (InterruptedException e2) {
                    e2.printStackTrace();
                }
            }
        }.start();
    }
    public String revertValue(int value) {
        int fir = value / 16;
        int sec = value % 16;
        String res = "00";
        StringBuffer sb = new StringBuffer(res);
        sb.append(CRC16.convertF(fir));
        sb.append(CRC16.convertF(sec));
        return sb.toString();
    }
    private String getResourcesUri(@DrawableRes int id) {
        Resources resources = getResources();
        String uriPath = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
                resources.getResourcePackageName(id) + "/" +
                resources.getResourceTypeName(id) + "/" +
                resources.getResourceEntryName(id);
        return uriPath;
    }
    public int getResourceByReflect(String imageName) {
        Class drawable = R.drawable.class;
        Field field = null;
        int r_id;
        try {
            field = drawable.getField(imageName);
            r_id = field.getInt(field.getName());
        } catch (Exception e) {
            r_id = R.drawable.a1;
            Log.e("ERROR", "PICTURE NOT　FOUND！");
        }
        return r_id;
    }
    Bitmap bm;
    PageS PageS = new PageS();
    static  public  SQLiteDatabase dbImage,db;
    static  public  SQLiteDatabase myDatabase;
    private SQLiteHelper dbHelper;
    private static String DB_MAGE_NAME = "image.db";
    private static String DB_BIN13_NAME = "bin13.db";
    private static String DB_NAME = "mycity.db";
    private static int DB_VERSION = 1;
    SQLiteDatabase Database;
    private Cursor cursor;
    public  static byte[][]  byte13Bin = new byte[200][48];
    public static int picturenum = 0;


    private void getFiles(String string) {
        // TODO Auto-generated method stub
        File file = new File(string);
        File[] files = file.listFiles();
        for (int j = 0; j < files.length; j++) {
            String name = files[j].getName();
            if (files[j].isDirectory()) {
                String dirPath = files[j].toString().toLowerCase();
                System.out.println(dirPath);
                getFiles(dirPath + "/");//if (files[j].isFile() & name.endsWith(".jpg") || name.endsWith(".png") || name.endsWith(".bmp") || name.endsWith(".gif") || name.endsWith(".jpeg"))
            } else if (files[j].isFile() & name.endsWith(".bmp")) {
                System.out.println("FileName===" + files[j].getName());
                picturenum++;
            }
        }
    }
    private boolean checkIsImageFile(String fName) {
        boolean isImageFile = false;
        String FileEnd = fName.substring(fName.lastIndexOf(".") + 1,fName.length()).toLowerCase();// 获取扩展名
        if (FileEnd.equals("bmp")) {
            isImageFile = true;
            picturenum++;
        } else {
            isImageFile = false;
        }
        return isImageFile;
    }
    List<String> pictureNameList = new ArrayList<String>();   // 图片列表
    private List<String> setPictureFromSDToDB() {
//          String filePath = "/mnt/external_sd/DWIN_SET";    // 得到sd卡内image文件夹的路径   File.separator(/)/storage/emulated/0
//        String filePath =  "/storage/emulated/0/DWIN_SET";
        String filePath =  "/storage/emulated/0/0CarControl/DWIN_SET";
        String picturePath = null;
        File fileAll = new File(filePath);     // 得到该路径文件夹下所有的文件
        File[] files = fileAll.listFiles();
        String pictureName = null;        // 将所有的文件存入ArrayList中,并过滤所有图片格式的文件
        dbHelper.DBUpgrade(db, --DB_VERSION, DB_VERSION,"TB_NAME_IMAGE");
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (checkIsImageFile(file.getPath())) {
                picturePath = file.getPath();
                pictureName = picturePath.substring(picturePath.lastIndexOf("/") +1,  picturePath.lastIndexOf(".")).toLowerCase();
                bm =  BitmapFactory.decodeFile(picturePath);
                /* if(bm.getHeight()>bm.getWidth()){
                    Matrix matrix=new Matrix();
                    matrix.postScale(1f, 1f); // 缩放原图
                    matrix.postRotate(90); // 向左旋转45度，参数为正则向右旋转
                    bm=Bitmap.createBitmap(bm,0,0,bm.getWidth(), bm.getHeight(),matrix,true);
                }*/
                PageS.bitmapbj = PageS.bitmapqj = bm;
                if(bm != null)
                   dbHelper.PutBitbmpToDataBase (bm,pictureName);
                pictureNameList.add(pictureName);
            }
        }
        return pictureNameList;  // 返回得到的图片列表
    }
    boolean spinFlag=false;
    private boolean getPicturesFormDB(){
        ArrayList<Drawable> drawables = new ArrayList<Drawable>();   //查询数据库
        Cursor c = db.query("TBNameimage", null, null, null, null, null, null);
        int aa =  c.getCount();//c.moveToPosition()
        int bbb =  c.getColumnCount();//c.moveToPosition()
        try {
            columnNames = c.getColumnNames();
        } finally {
        }
        int ll = c.getColumnIndex(SQLiteHelper.PictureColumns.NAME) ;
        if(c != null && c.getCount() != 0) {
            while(c.moveToNext()) {
                //获取数据
               int cPosition = c.getPosition()-1;
                int tt = c.getColumnIndexOrThrow(SQLiteHelper.PictureColumns.NAME);
                   String pictureName = c.getString(tt);
                int pictureNameId = Integer.valueOf(pictureName).intValue();
                    byte[] bitmapData = c.getBlob(c.getColumnIndexOrThrow(SQLiteHelper.PictureColumns.PICTURE));
                    //将获取的数据转换成drawable
                    Bitmap pictureBitmap = BitmapFactory.decodeByteArray(bitmapData, 0,bitmapData.length, null);
                    PageS.height= pictureBitmap.getHeight();
                    PageS.width=  pictureBitmap.getWidth();
                     if( PageS.height> PageS.width){
                         spinFlag=true;
                         Matrix matrix = new Matrix();
                         matrix.postScale(1f, 1f); // 缩放原图
                         matrix.postRotate(90); // 向左旋转45度，参数为正则向右旋转
                         pictureBitmap = Bitmap.createBitmap(pictureBitmap, 0, 0, pictureBitmap.getWidth(), pictureBitmap.getHeight(), matrix, true);
                     }
                    BitmapDrawable bitmapDrawable = new BitmapDrawable(pictureBitmap);
                    drawable1 = bitmapDrawable;
                    drawables.add(drawable1);
                    if(pictureNameId<20) {
                        PageS.page[pictureNameId].frontBitmap = pictureBitmap;
                    }
                  if(pictureNameId>=20) {
                      PageS.page[pictureNameId-20].bgrdBitmap = pictureBitmap;
                  }
                  // PageS.page[pictureNameId].bgrdBitmap =  pictureBitmap;
                  //  PageS.bitmapbj = PageS.bitmapqj = bitp = bitmapDrawable.getBitmap();
            }
        }
       return  true;
    }
   int BinbyteNum(int num) {
        int interceptLenght;
        switch(num){
        case 0: //基础按键
            interceptLenght = 16;
            break;
        case 2: //增量调节
            interceptLenght = 32;
            break;
        case 5: //按键返回
            interceptLenght = 32;
            break;
        case 8: //同步调节
            interceptLenght = 48;
            break;
       default:
           interceptLenght = 32;
        }
    return interceptLenght;
    }
    int cntmun;
    public void setBinFormSDToDB(){
        try {
            File targetFile=new File("/mnt/external_sd/DWIN_SET/13触控配置文件.bin");
            //   File targetFile=new File("/storage/emulated/0/DWIN_SET/13触控配置文件.bin");
            if(!targetFile.exists()){
                targetFile.createNewFile();
            }else{
                InputStream in = new BufferedInputStream(new FileInputStream(targetFile));
                BufferedReader br= new BufferedReader(new InputStreamReader(in, "ISO-8859-1"));
                int  size = 0;
                byte[] targets = new byte[5000];
                size = in.available();
                in.read(targets,0,size);
                dbHelper.DBUpgrade(db, --DB_VERSION, DB_VERSION,"TB_NAME_BIN13");
               byte[] bytedb = new byte[48];
               int interceptLenght=0;
               int  interceptCnt=0;
                cntmun=0;
                for(interceptCnt=0;interceptCnt<size-2;) {
                   interceptLenght =  BinbyteNum(targets[interceptCnt+15]);
                    System.arraycopy(targets, interceptCnt, bytedb, 0, interceptLenght);
                    interceptCnt += interceptLenght;
                    cntmun++;
                    dbHelper.Put13BinToDataBase (bytedb);
                }
                br.close();
                in.close();
            }
        }catch(Exception e){
            e.printStackTrace();  Toast.makeText(MainActivityf.this,e.toString(),Toast.LENGTH_LONG).show();
        }
    }
    public  static HashMap<String, Integer> feedPicID = new HashMap<String, Integer>();
    public  static HashMap<String, Integer> feedIconID = new HashMap<String, Integer>();
    private boolean getBinForDB() { //查询数据库
        try {
        Cursor iCursor = db.query("TBNamebin13", null, null, null, null, null, null);
        int totalIconNum = iCursor.getCount();
        int iCursorNUm = 0;
        //遍历数据
        if (iCursor != null && totalIconNum != 0) {
            for (iCursorNUm = 0; iCursorNUm < totalIconNum; iCursorNUm++) {
                iCursor.moveToNext();
                byte[] byteiCursor = iCursor.getBlob(iCursor.getColumnIndexOrThrow(SQLiteHelper.PictureColumns.BIN));
                for (int ii = 0; ii < BinbyteNum(byteiCursor[15]); ii++) {
                     byte13Bin[iCursorNUm][ii] = byteiCursor[ii];
                }
            }
        }
        int rectLeft, rectTop, rectRight, rectBottom,rectBottomtemp;
        int currtId, lastID;
        PageS.page[0].totalIconNum = 0;
        //for( int kk=0;kk< PageS.page[0].totalIconNum;kk++) {
        lastID = 100;
        int iconId=0,temp=0;
        Picture.totalPictureNum = 0;
        int IconNumtemp=0;
        byte[] cmdbytetrmp = new byte[2];
         String   feedBackAddrStr=null;
        for (int ii = 0; ii < totalIconNum; ii++) {
            currtId = byte13Bin[ii][1];
            if (currtId != lastID) {
                PageS.page[currtId].id = currtId;
                PageS.page[currtId].bgrdId = byte13Bin[ii][13];
                Picture.totalPictureNum++;
                IconNumtemp = 0;
                iconId=0;
            }
            lastID = currtId;
            rectLeft = (((byte13Bin[ii][2] & 0xff) << 8) + (byte13Bin[ii][3] & 0xff));
            rectTop = (((byte13Bin[ii][4] & 0xff) << 8) + (byte13Bin[ii][5] & 0xff));
            rectRight = (((byte13Bin[ii][6] & 0xff) << 8) + (byte13Bin[ii][7] & 0xff));
            rectBottom = (((byte13Bin[ii][8] & 0xff) << 8) + (byte13Bin[ii][9] & 0xff));
            PageS.page[currtId].icon[IconNumtemp].jumpid = ((byte13Bin[ii][10] & 0xff) << 8) + (byte13Bin[ii][11] & 0xff);
            PageS.page[currtId].icon[IconNumtemp].backgrdId = ((byte13Bin[ii][12] & 0xff) << 8) + (byte13Bin[ii][13] & 0xff);
            PageS.page[currtId].icon[IconNumtemp].isReport = byte13Bin[ii][14];
            PageS.page[currtId].icon[IconNumtemp].buttonType = byte13Bin[ii][15];
            PageS.page[currtId].icon[IconNumtemp].belongsToPicId = currtId;
            PageS.page[currtId].icon[IconNumtemp].feedBackAddrStr = "0000";
            PageS.page[currtId].icon[IconNumtemp].touchDowncmdStr="0000";
            PageS.page[currtId].icon[IconNumtemp].touchUpcmdStr="0000";
            if((byte13Bin[ii][15]==2)||(byte13Bin[ii][15]==5)) {

                cmdbytetrmp[0] = byte13Bin[ii][17];
                cmdbytetrmp[1] = byte13Bin[ii][18];
                PageS.page[currtId].icon[IconNumtemp].touchDowncmdStr= toHex(cmdbytetrmp, 2).toString();
                  feedBackAddrStr = toHex(cmdbytetrmp, 1).toString().substring(0,1)
                                +"00"+toHex(cmdbytetrmp, 1).toString().substring(1,2);
                        PageS.page[currtId].icon[IconNumtemp].feedBackAddrStr = feedBackAddrStr;
               PageS.feedType.put(feedBackAddrStr,"1");
                feedPicID.put(feedBackAddrStr,currtId);
                feedIconID.put(feedBackAddrStr,IconNumtemp);

            }
            PageS.page[currtId].icon[IconNumtemp].iconId=IconNumtemp;
            if(byte13Bin[ii][15]==8) {
                cmdbytetrmp[0] = byte13Bin[ii][0x24];
                cmdbytetrmp[1] = byte13Bin[ii][0x25];
                PageS.page[currtId].icon[IconNumtemp].touchUpcmdStr= toHex(cmdbytetrmp, 2).toString();
                cmdbytetrmp[0] = byte13Bin[ii][0x14];
                cmdbytetrmp[1] = byte13Bin[ii][0x15];
                PageS.page[currtId].icon[IconNumtemp].touchDowncmdStr = toHex(cmdbytetrmp, 2).toString();
            }
            if(spinFlag) {
                rectBottomtemp = rectBottom;
                rectBottom = rectRight;
                rectRight = PageS.height - rectTop;
                rectTop = rectLeft;
                rectLeft = PageS.height-rectBottomtemp;//if( PageS.height> PageS.width) {
                PageS.page[currtId].icon[IconNumtemp].iconRect = new Rect(rectLeft * screenWidth / PageS.height, rectTop * screenHeight / PageS.width,
                        rectRight * screenWidth / PageS.height, rectBottom * screenHeight / PageS.width);
            }
            else {
                PageS.page[currtId].icon[IconNumtemp].iconRect = new Rect(rectLeft * screenWidth / PageS.width, rectTop * screenHeight / PageS.height,
                        rectRight * screenWidth / PageS.width, rectBottom * screenHeight / PageS.height);
            }
            if (PageS.page[currtId].frontBitmap != null)
                PageS.page[currtId].icon[IconNumtemp].iconqj = Bitmap.createBitmap(PageS.page[currtId].frontBitmap, rectLeft, rectTop,rectRight - rectLeft, rectBottom - rectTop);
            if (PageS.page[currtId].bgrdBitmap != null)
                PageS.page[currtId].icon[IconNumtemp].iconbj  = Bitmap.createBitmap(PageS.page[currtId].bgrdBitmap, rectLeft, rectTop,  rectRight - rectLeft, rectBottom - rectTop);
            if (PageS.page[currtId].bgrdBitmap == null){
                PageS.page[currtId].icon[IconNumtemp].iconbj = Bitmap.createBitmap(PageS.page[currtId].frontBitmap, rectLeft, rectTop,rectRight - rectLeft, rectBottom - rectTop);
            }
            //   PageS.page[currtId].icon[IconNumtemp].iconRect = new Rect(rectLeft, rectTop, rectRight, rectBottom);
            //   PageS.page[currtId].icon[IconNumtemp].iconRect=  convertRect(PageS.page[currtId].icon[IconNumtemp].iconRect);
           // screenHeight=800;

            PageS.page[currtId].totalIconNum++;
            IconNumtemp++;
        if(IconNumtemp>=29){
            IconNumtemp = 29;
        }
            if(currtId>=29){
                currtId = 29;
            }
        }
     }
        catch (Exception e) {
            Toast.makeText(MainActivityf.this,e.toString(),Toast.LENGTH_LONG).show();
        }
        return  true;
    }
    public  Rect convertRect(Rect old){
        return  new Rect(convertWn(old.left),convertHn(old.top),convertWn(old.right),convertHn(old.bottom));
    }
    Bitmap bitp=null;
    Drawable drawable,drawable1;
    String[] columnNames = new  String[10];
    double widthScale,heightScale;
    static int screenWidth ;
    static int screenHeight ;
    static int naviHeight;
    private int getNavigationBarHeight() {
        Resources resources =  MainActivityf.this.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height","dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        Log.v("dbw", "Navi height:" + height);
        return height;
    }
    //获取是否存在NavigationBar

    static public boolean checkDeviceHasNavigationBar() {
        boolean hasNavigationBar = false;
        try {
            //MainActivitycontext =  getApplicationContext();
        Resources rs = MainActivitycontext.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
           Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
             }
        } catch (Exception e) {
           // Toast.makeText(MainActivityf.this,e.toString(),Toast.LENGTH_LONG).show();
        }
        return hasNavigationBar;
    }
    private void showNavigationBar() {
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_VISIBLE;
        decorView.setSystemUiVisibility(uiOptions);
    }
    private void hideNavigationBar() {
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
    }
    public static boolean checkNavigationBarShow(@NonNull Context context, @NonNull Window window){
        boolean show;
        Display display = window.getWindowManager().getDefaultDisplay();
        Point point = new Point();
        display.getRealSize(point);

        View decorView = window.getDecorView();
        Configuration conf = context.getResources().getConfiguration();
        if (Configuration.ORIENTATION_LANDSCAPE == conf.orientation) {
            View contentView = decorView.findViewById(android.R.id.content);
            show = (point.x != contentView.getWidth());
        } else {
            Rect rect = new Rect();
            decorView.getWindowVisibleDisplayFrame(rect);
            show = (rect.bottom != point.y);
        }
        return show;
    }
static  boolean checkDeviceHasNavigationBarFlag;
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            checkDeviceHasNavigationBarFlag=true;
        } else {
            checkDeviceHasNavigationBarFlag=false;
        }
    }
    public static boolean checkDeviceHasNavigationBar(Context activity) {
        //通过判断设备是否有返回键、菜单键(不是虚拟键,是手机屏幕外的按键)来确定是否有navigation bar
        boolean hasMenuKey = ViewConfiguration.get(activity)
                .hasPermanentMenuKey();
        boolean hasBackKey = KeyCharacterMap
                .deviceHasKey(KeyEvent.KEYCODE_BACK);

        if (!hasMenuKey && !hasBackKey) {
            // 做任何自己需要做的,这个设备有一个导航栏
            return true;
        }
        return false;
    }
    public static boolean checkHasNavigationBar() {
        WindowManager windowManager = activityf.getWindowManager();
        Display d = windowManager.getDefaultDisplay();

        DisplayMetrics realDisplayMetrics = new DisplayMetrics();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            d.getRealMetrics(realDisplayMetrics);
        }

        int realHeight = realDisplayMetrics.heightPixels;
        int realWidth = realDisplayMetrics.widthPixels;

        DisplayMetrics displayMetrics = new DisplayMetrics();
        d.getMetrics(displayMetrics);

        int displayHeight = displayMetrics.heightPixels;
        int displayWidth = displayMetrics.widthPixels;

        return (realWidth - displayWidth) > 0 || (realHeight - displayHeight) > 0;
    }
    static Context MainActivitycontext;
    static public Activity activityf;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        frame = (myFrameLayout) findViewById(R.id.gridlayout1);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int checkPermission = this.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
            if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
                    requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},101);
                } else {
                    requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},101);
                }
                return;
            }
        }

        Log.e("init===2", "===");

        /**
         *
         * 读写手机状态和身份
         *
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int checkPermission = this.checkSelfPermission(Manifest.permission.READ_PHONE_STATE);
            if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                if (shouldShowRequestPermissionRationale(Manifest.permission.READ_PHONE_STATE)) {
                    requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 100);
                } else {
                    requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 100);
                }
                return;
            }
        }

        Log.e("init===3", "===");

        // <!-- 写入扩展存储，向扩展卡写入数据，用于写入离线定位数据 -->
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int checkPermission = this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
            if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                if (shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
                } else {
                    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
                }
                return;
            }
        }

        if (Build.VERSION.SDK_INT >= 23) {
            int checkPermission = checkSelfPermission(Manifest.permission.CAMERA);
            if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
                    requestPermissions(new String[]{Manifest.permission.CAMERA}, 102);
                } else {
                    requestPermissions(new String[]{Manifest.permission.CAMERA}, 102);
                }
                return;
            }
        }




       PageS.setfeeds();
        dbHelper = new SQLiteHelper(this, DB_NAME, null, DB_VERSION);
        db = dbHelper.getWritableDatabase(); /* 创建表 */	//调用SQLiteHelper.OnCreate()

        Log.e("init===4", "===");

          drawable = getResources().getDrawable(R.drawable.a1);
        BitmapDrawable bmpDraw = (BitmapDrawable) drawable;
        bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.a1);
        MainActivitycontext = getApplicationContext();
        drawable = getResources().getDrawable(R.drawable.a21);
        bmpDraw = (BitmapDrawable) drawable;
        int len = R.drawable.class.getDeclaredFields().length;
        DisplayMetrics dm = new DisplayMetrics();
          activityf=MainActivityf.this;
        //checkHasNavigationBar();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;
        naviHeight = getNavigationBarHeight();
        hideNavigationBar();


          WindowManager mWM = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
        LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //View mMainView = inflater.inflate(R.layout.main, null);

        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);//显示的优先级可以调整，显示的顺序可以查看WindowManagerPolicy中getWindowLayerFromTypeLw函数中的返回值
        lp.x = 0;//显示的起始位置x
        lp.y = 0;//显示的起始位置y
        lp.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN;
        lp.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                View.SYSTEM_UI_FLAG_FULLSCREEN |
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY |
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
          dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;

        String extSdcardPath = System.getenv("SECONDARY_STORAGE");
        File sdDir = null;
        sdDir =Environment.getExternalStorageDirectory();
        String sdpath = sdDir.getAbsolutePath();//"/storage/emulated/0"
            //try {
            ;
             setPictureFromSDToDB();
              setBinFormSDToDB();
            //   }
            // catch (Exception e) {
            // Toast.makeText(MainActivityf.this,e.toString(),Toast.LENGTH_LONG).show();
            // }
        getPicturesFormDB();
        getBinForDB();

        Log.e("init===5", "===");

        int flags;
       // flags =   View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
       // getWindow().getDecorView().setSystemUiVisibility(flags);

       // WindowManager.LayoutParams params = MainActivityf.this.getWindow().getAttributes();
      //  int paramsFlag = params.flags & (~WindowManager.LayoutParams.FLAG_FULLSCREEN);


        BitmapFactory.Options bfoOptions = new BitmapFactory.Options();
        bfoOptions.inScaled = false;
        refreshui(currentPage);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
        dm = new DisplayMetrics();        //设置妹子显示的位置
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        userInfo =  getSharedPreferences("user_info",
                MODE_PRIVATE);
        testtView = new TextView(this);
        //这里的Textview的父layout是ListView，所以要用ListView.LayoutParams
        testtView.setPadding(20, 0, 20, 0);
        testtView.setText("this is used for testing");
        testtView.setTextColor(getResources().getColor(R.color.colorAccent));
        testtView.setTextSize(18);
        LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        testtView.setLayoutParams(params);
        this.addContentView(testtView,params);
        testtView.setVisibility(View.INVISIBLE);
        //  AsyncTaskRunner runner = new AsyncTaskRunner();
        //  runner.execute();
    }
    int getCurSel(int x,int y){
     for (int w=0; w<PageS.page[PageS.pageno].totalIconNum;w++){
         if (PageS.page[PageS.pageno].icon[w].iconRect.contains(x,y)){
            return  w;
         }
     }
        return  -1;
    }

    @Override
    protected void onDestroy() {
        uartJnit.sclose();
        super.onDestroy();
    }
    @Override
    protected void onPause() {
        super.onPause();
    }
    @Override
    public void onProgressChanged(SeekBar seekBarx, int progress,
                                  boolean fromUser) {
        int tmp = (int) seekBarx.getTag();
        int firpara = progress / 10 ;
        String myvalue = revertValue(firpara * 10);
        if (feedOK(PageS.allDArray[15+tmp])) {
            PageS.feedMap.put(PageS.allDArray[15+tmp], revertValue(firpara * 10));
        }
        if(firpara < 10) {
            String cmdx = PageS.sliderCmd[tmp][firpara];
            if (progress % 10 == 0) {
                try {
                    slidersend(tmp, firpara);
                }
                catch(Exception ex){
                    return;
                }
            }
        }
    }
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
    }
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
    }
    @Override
    protected void onStart() {
        super.onStart();
        MeziView.fristFlag = true;

        userInfo.registerOnSharedPreferenceChangeListener(mListener);
    }
    @Override
    protected void onStop() {
        userInfo.unregisterOnSharedPreferenceChangeListener(mListener);
        super.onStop();
    }
    @Override
    protected void onResume(){

     /* if(spinFlag){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
      else  {
          setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
      }*/
        fd =  uartJnit.getInstance().fd;
        super.onResume();


        handler.postDelayed(runnable, 10);

        Log.e("onResume===", "===");
    }
    public void removeAll(){
        if (frame != null) {
            frame.removeAllViews();
            frame.invalidate();
        }

    }
    public  void createSeekb(){
        seekBar = new SeekBar(this);
        seekBar.setThumb(getDrawable(R.drawable.thumb_image));
        seekBar.setProgressDrawable(getDrawable(R.drawable.adjust));
        seekBar.setMinimumHeight(convertHn(3));
        seekBar.setThumbOffset(0);
        FrameLayout.LayoutParams headParams = new FrameLayout.LayoutParams(convertWn(376), convertHn(46));
        headParams.setMargins(convertWn(566), convertHn(163), convertWn(936), convertHn(198));
        seekBar.setLayoutParams(headParams);
        frame.addView(seekBar);
        seekBar.bringToFront();
        seekBar.setSplitTrack(false);
        seekBar.setOnSeekBarChangeListener(this);
        seekBar1 = new SeekBar(this);
        seekBar.setMax(100);
        seekBar1.setThumb(getDrawable(R.drawable.thumb_image));
        seekBar1.setProgressDrawable(getDrawable(R.drawable.adjust));
        seekBar1.setMinimumHeight(convertHn(3));
        seekBar1.setOnSeekBarChangeListener(this);
        seekBar1.setThumbOffset(0);
        FrameLayout.LayoutParams headParams1 = new FrameLayout.LayoutParams(convertWn(376), convertHn(46));
        headParams1.setMargins(convertWn(566), convertHn(268), convertWn(936), convertHn(303));
        seekBar1.setLayoutParams(headParams1);
        frame.addView(seekBar1);
        seekBar1.bringToFront();
        seekBar1.setSplitTrack(false);
        seekBar2 = new SeekBar(this);
        seekBar2.setThumb(getDrawable(R.drawable.thumb_image));
        seekBar2.setProgressDrawable(getDrawable(R.drawable.adjust));
        seekBar2.setMinimumHeight(convertHn(3));
        seekBar2.setOnSeekBarChangeListener(this);
        seekBar2.setThumbOffset(0);
        seekBar.setTag(0);
        seekBar1.setTag(1);
        seekBar2.setTag(2);
        FrameLayout.LayoutParams headParams2 = new FrameLayout.LayoutParams(convertWn(376), convertHn(46));
        headParams2.setMargins(convertWn(566), convertHn(360), convertWn(936), convertHn(395));
        seekBar2.setLayoutParams(headParams2);
        frame.addView(seekBar2);
        seekBar2.bringToFront();
        seekBar2.setSplitTrack(false);
        for (int hh=0;hh<3;hh++) {
            String tmpStat = PageS.feedMap.get(PageS.allDArray[hh+15]);
            if (!tmpStat.equals("0000")) {
                dish(PageS.allDArray[hh+15], tmpStat);
            }
        }
    }
    public static String toHex(byte[] buffer,int read_count) {
        StringBuffer sb = new StringBuffer(read_count * 2);
        for (int i = 0; i < read_count; i++) {
            sb.append(Character.forDigit((buffer[i] & 240) >> 4, 16));
            sb.append(Character.forDigit(buffer[i] & 15, 16));
        }
        return sb.toString();
    }
    public int convertHn(int old ) {
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.widthPixels; //1280
        int screenHeight = dm.heightPixels;////728
        int newx = (old * screenHeight) / PageS.height;
        return newx;
    }
    public int convertWn(int oldx) {
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;
        int newx = oldx * screenWidth / PageS.width;;
        return newx;
    }
    public  void createV(){
        testfView = new TextView(this);
        testfView.setText("0.0");
        String tmpStat = PageS.feedMap.get(PageS.allDArray[14]);
        if(!tmpStat.equals("0000")){
            disv(PageS.allDArray[14],tmpStat);
        }
        Typeface typeface= Typeface.createFromAsset(getAssets(),"yj.ttf");
        testfView.setTypeface(typeface);//第一句话“离离原上草，一岁一枯荣”引入lanti.ttf字体库
        testfView.setTextColor(getResources().getColor(R.color.colorPrimary));
        testfView.setTextSize(80);
        int mWidth = testfView.getMeasuredWidth();
        int mHeight = testfView.getMeasuredHeight();
        FrameLayout.LayoutParams paramsf=new FrameLayout.LayoutParams(convertWn(204),convertHn(114));
        paramsf.leftMargin = convertWn(687) + mWidth/2 ;
        paramsf.topMargin = convertHn(186) +  mHeight / 2;
        testfView.setLayoutParams(paramsf);
        frame.addView(testfView,paramsf);
        testView = new TextView(this);
        testView.setText("0.0V");
        String ftmpStat = PageS.feedMap.get(PageS.allDArray[13]);
        if(!ftmpStat.equals("0000")){
            disv(PageS.allDArray[13],ftmpStat);
        }
        testView.setTypeface(typeface);//第一句话“离离原上草，一岁一枯荣”引入lanti.ttf字体库
        testView.setTextColor(getResources().getColor(R.color.colorPrimary));
        testView.setTextSize(80);
        FrameLayout.LayoutParams params=new FrameLayout.LayoutParams( convertWn(204),convertHn(114));
        int tWidth = testfView.getMeasuredWidth();
        int tHeight = testfView.getMeasuredHeight();
        params.leftMargin = convertWn(200) + tWidth/2 ;
        params.topMargin = convertHn(166) +  tHeight / 2;
        testView.setLayoutParams(params);
        frame.addView(testView,params);
    }
    ////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////
    // //////////////////////////////////////////////////////////////////////////   // //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
    // //////////////////////////////////////////////////////////////////////////
    public  void addmezis(int tagetPageId){
           Rect tmprecto = new Rect() ;
          for (int w=0; w< PageS.page[tagetPageId].totalIconNum;w++) {
            tmprecto = PageS.cmdRect[w];
            MeziView mezii = new MeziView(MainActivityf.this);
            mezii.mleft = convertWn(tmprecto.left);
            mezii.mtop = convertHn(tmprecto.top);
            mezii.mwidth = convertWn(tmprecto.width());
            mezii.mheight = convertHn(tmprecto.height());
            mezii.mRect =  PageS.page[tagetPageId].icon[w].iconRect;

            String addr = PageS.feedDArray[w];
            boolean bool1 = PageS.feedMap.containsKey(addr);
            String tmpS = PageS.feedMap.get(addr);
            boolean bool2 = (tmpS == null)? false:(tmpS.equals("0001"));
            mezii.type = PageS.nodeArray[w];
            mezii.iconNum=0;
           if(PageS.page[tagetPageId].icon[w].isfeedBack==true) {
               mezii.mResBitmap = PageS.page[tagetPageId].icon[w].iconbj;
           }
           else {
               mezii.mResBitmap = PageS.page[tagetPageId].icon[w].iconqj;
           }

            mezii.setId(w + 1);
            frame.addView(mezii,w);
           // if(bool1 && bool2){
               // mezii.mRes = PageS.onArray[w];
                 mezii.repaint();
          //  }
        }
    }
    void refreshui(int tagetPage){
        removeAll();
        pagestatus.setInit(tagetPage);
        currentPage = tagetPage;
        mezi = new MeziView(MainActivityf.this);
        mezi.mleft = convertWn(0);
        mezi.mtop = convertHn(0);
        mezi.mwidth = convertWn(10);
        mezi.mheight = convertHn(10);
        mezi.type = 1;
        mezi.iconNum=0;
        mezi.mRect = new Rect(0, 0,  mezi.mwidth, mezi.mheight);
        mezi.setClickable(true);
        mezi.setId(0);
        mezi.setOnTouchListener(new TouchListenerx());
        frame.setEnabled(false);
        frame.addView(mezi,-1);
        // frame.setBackgroundResource(PageS.pageback);

        drawable = new BitmapDrawable( bm);
        // Context context = getApplicationContext();
        // pictureDatabase = new  PictureDatabase(MainActivityf.this);

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.a1);
        // pictureDatabase.PutBitbmpToDataBase(bitmap);
        //  Context mcontext = getApplicationContext();
        // File file =  mcontext.getFilesDir() ;
        // SQLiteDatabase db = getReadableDatabase();
        //   db = getWritableDatabase();
        BitmapDrawable bitmapDrawable = new BitmapDrawable( PageS.page[tagetPage].frontBitmap);
        frame.setBackground(bitmapDrawable);
        addmezis(tagetPage);
        if(tagetPage == 0) {
            createSeekb();
        }
        if(tagetPage == 2) {
            createV();
        }
    }
    private  void testFeed(int picId1,int icoId1,boolean onff){
        //if((picId1 == PageS.pageno)&& (picId1 != -1)&&(icoId1 != -1)) {
            if((picId1 != -1)&&(icoId1 != -1)) {
            newm = (MeziView) frame.getChildAt(icoId1);
            //String aaaa = newm.getId() + "|" + myPosition;
            //   Log.e("feedTest", aaaa);
            if (newm != null) {
                if (bitmap != null)
                    if (onff) {
                        if(picId1 == PageS.pageno){
                        newm.mResBitmap = PageS.page[picId1].icon[icoId1].iconbj;}
                        PageS.page[picId1].icon[icoId1].isfeedBack= true;
                    } else {
                        if(picId1 == PageS.pageno){
                        newm.mResBitmap = PageS.page[picId1].icon[icoId1].iconqj;}
                        PageS.page[picId1].icon[icoId1].isfeedBack= false;
                    }
                MeziView.fristFlag = false;
                newm.repaint();
            }
        }
    }
    private  void testsFeed(int picId,int icoId,boolean onff){
       // if(myPosition >= 0) {
           newm = (MeziView) frame.getChildAt(icoId);
          //   String aaaa = newm.getId() + "|" + picId;
           //Log.e("feedTest", aaaa);
            if (newm != null) {
                newm.touchFlag=true;//false;//
                newm.mDrawFinish=false;
                newm.mRadius=360;
                newm.mDrawRadius =0;//
                //newm.iconNum = myPosition;
                testFeed(picId,icoId,onff);
       //     }
        }
    }



    private class TouchListenerx implements View.OnTouchListener {
        private boolean longClicked;
        private boolean upClicked;
        private int downtimes = 0;
        private int uptimes = 0;
        private int failTime;
        private TouchListenerx() {
        }
        public boolean onTouch(View v, MotionEvent event) {//触摸按下了
            int x = (int) event.getX(); int y = (int) event.getY();
            currentPosition =  PageS.page[PageS.pageno].currtConNum = getCurSel(x,y);
            Log.e("touchTAG", "view:"  + v.getId());
            if(currentPosition!=-1){
                mezi.mInitX = PageS.cmdRect[currentPosition].exactCenterX();
                mezi.mInitY = PageS.cmdRect[currentPosition].exactCenterY();
                String cmdOne = PageS.cmdArray[currentPosition];
                  cmdOne =  PageS.page[PageS.pageno].icon[currentPosition].touchDowncmdStr + "0000";
                  int buttonType = PageS.page[PageS.pageno].icon[currentPosition].buttonType;
              if (( buttonType == 0x00)||( buttonType == 0x05)){//跳转界面
                   cmdOne = Integer.toString(PageS.page[PageS.pageno].icon[currentPosition].jumpid);
                    Message msg = new Message();
                    msg.what = 3;
                    msg.obj = cmdOne;
                    Bundle bundle = new Bundle();
                    bundle.putString("jmppageno", cmdOne);
                    msg.setData(bundle);
                    mHandler.sendMessage(msg);
                    return  true;
                }
                String allCmdx = cmdheader;
                String tmpTmp = cmdOne;
                allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
                StringBuffer allCmd = CRC16.crc16x(allCmdx);
             final  String cmd = allCmd.substring(0,22);
                longClicked = false;
                upClicked = false;
                if (event.getAction() == MotionEvent.ACTION_DOWN) {//按下按键
                    mezi.mDrawFinish = false;
                    mezi.mDrawBack = true ;
                    mezi.mRadius =360;
                    mezi.postOnAnimation11();
                    testsFeed(PageS.pageno,PageS.page[PageS.pageno].icon[currentPosition].iconId,true);
                    new Thread() {
                        public void run() {
                            super.run();
                            if (!longClicked) {
                                try {
                                    boolean isSendx = false;
                                    if (downtimes < 1) {
                                        downtimes = downtimes++;
                                        isSendx = uartJnit.getInstance().sendCmds(cmd);
                                        longClicked = true;
                                    }
                                    Log.e("send TAG", "send down: " + cmd);
                                    Message msg = new Message();
                                    if (isSendx) {
                                        msg.what = 1;
                                        longClicked = true;
                                        Log.e("send TAG", "send down" + cmd + "success");
                                    } else {
                                        Log.e("TAG", "send down  :" + cmd + "failed!");
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                try {
                                    Thread.sleep((long) TIMER_INTERVAL);
                                } catch (InterruptedException e2) {
                                    e2.printStackTrace();

                                }
                            }
                        }
                    }.start();
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    testsFeed(PageS.pageno,PageS.page[PageS.pageno].icon[currentPosition].iconId,false);
                    tmpTmp="0000";

                    Log.e("onTouch==1", upClicked+"===" + PageS.page[PageS.pageno].icon[currentPosition].buttonType+"===" +PageS.page[PageS.pageno].icon[currentPosition].iconId);

                    if ((!upClicked)&&(PageS.page[PageS.pageno].icon[currentPosition].buttonType==8)) {
                        tmpTmp = PageS.page[PageS.pageno].icon[currentPosition].touchUpcmdStr + "0000";
                        allCmdx = cmdheader;
                        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
                        allCmd = CRC16.crc16x(allCmdx);
                      }
                    final String downCmd = allCmd.substring(0, 22);
                    new Thread() {
                        public void run() {
                            super.run();
                            if ((!upClicked)&&(PageS.page[PageS.pageno].icon[currentPosition].buttonType==8)) {
                                    try {
                                        if (downCmd.length() == 22) {
                                            boolean isSendy = false;
                                            //Log.e("TAG", "send  dian:" + TransformUtils.getExchangeCmd(downCmd));
                                            if (uptimes < 1) {
                                                uptimes = uptimes++;
                                                isSendy = uartJnit.getInstance().sendCmds(downCmd);
                                                upClicked = true;
                                            }
                                            Message msg = new Message();
                                            if (isSendy) {
                                                msg.what = 1;
                                                msg.obj = currentPosition;
                                                upClicked = true;
                                                Log.e("TAG", "send dian:" + downCmd + "success");
                                            } else {
                                                Log.e("TAG", "send dian " + downCmd + " failed!");
                                            }
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                         }
                        }
                    }.start();
//                    try {
////                        Thread.sleep((long) TIMER_INTERVAL);
//                        Thread.sleep((long)500);
//                    } catch (InterruptedException e2) {
//                        e2.printStackTrace();
//                    }

                    handler.postDelayed(runnable,1000); // readFeedback();//
                }
            }
            return  true;
        }
    }

    Runnable runnable=new Runnable(){
        @Override
        public void run() {
            readFeedback();
        }
    };
    public int readFeedback() {
        String tmpstr = "";
        String feedCamdstr = "";
        String feedCamdFalgstr = "";
        try {
            Log.e("readFeedback===00", fd+"==="+read_buf);

            int read_count = uartJni.read(fd, read_buf, read_buf.length);

            Log.e("readFeedback===0", read_count+"==="+toHex(read_buf, read_count));

//            if (read_count < 0) {
//                read_count = 0; }
//            if (read_count > 60) {
//                read_count = 60;  }
            tmpstr = toHex(read_buf, read_count).toString();

            Log.e("readFeedback===", "==="+tmpstr);
        } catch (Exception ex) {
        }
        if (!tmpstr.equals("")) {
            Message cmdmsg = new Message();
            cmdmsg.what = 1;
            Bundle bcmd = new Bundle();
            int index, index82, index5a;
            int cmdlenght;
            int tmpstrlenght = read_buf.length;

            index = tmpstr.indexOf("82");
            if (index >= 6) {
                index = index-6;
                if (index != -1) {
                    cmdlenght = ((int) tmpstr.charAt(index + 4) - 48) * 16 + (int) tmpstr.charAt(index + 5) - 48;
                    feedCamdstr = tmpstr.substring(index, index + (cmdlenght + 3) * 2);
                    bcmd.putString("alltext", feedCamdstr);
                    cmdmsg.setData(bcmd);
                    boolean xx = uHandler.sendMessage(cmdmsg);
                }
            }
        }
        //   handler.postDelayed(runnable, 100);
        return 1;
    }

    @SuppressLint("HandlerLeak")
    public Handler uHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    break;
                case 1:
                    String commandTxt = msg.getData().getString("alltext");

                    Log.e("uHandler===1", "==="+commandTxt);

                    testtView.setText(commandTxt);
                    if (commandTxt.length() > 10) {
                        try {
                            refreshallui(commandTxt);
                        } catch (Exception ex) {
                            return;
                        }

                    }
                    break;
                default:
                    break;
            }
        }
    };

    private void refreshallui(String comingdata) {
        Log.e("refreshallui===", checkability(comingdata)+"==="+comingdata);

        if (!checkability(comingdata)) {
            return;
        }
        String message = "";
        if (comingdata.length() >= 40) {
            message = comingdata.substring(0, 40);
        } else {
            message = comingdata;
        }
        String firstFour = "";
        if ((message.length()) > 4) {
            firstFour = message.substring(0, 4);
        }
        int positionInBoard = 0;
        int counts = 0;
        if (message.length() > 19) {
            int msgcounts = Integer.parseInt(message.substring(4, 6), 16);
            counts = (msgcounts - 7) / 2 + 1;
            String[] feedDevice = new String[counts];
            String[] feedStatus = new String[counts];

            Log.e("refreshallui===1", counts+"==="+PageS.feedType);

            if (counts == 1) {
                String feedDevicex = message.substring(8, 12);
                String deviceStaus = message.substring(12, 16);
                Message msg = new Message();
                String ntype = PageS.feedType.get(feedDevicex);

                Log.e("refreshallui===1_1", counts+"==="+ntype+"==="+feedDevicex+"==="+deviceStaus);

                msg.what = Integer.parseInt(ntype);
                Bundle bundle = new Bundle();
                bundle.putString("feedDevice", feedDevicex);
                bundle.putString("feedStatus", deviceStaus);
                msg.setData(bundle);
                if (feedOK(feedDevicex)) {
                    PageS.feedMap.put(feedDevicex, deviceStaus);
                }
                mHandler.sendMessage(msg);
            } else {
                for (int cc = 0; cc < counts; cc++) {
                    feedDevice[cc] = TransformUtils.getAddress(message.substring(8, 12), cc);
                    feedStatus[cc] = message.substring(12 + cc * 4, 16 + cc * 4);

                    Log.e("refreshallui===2", counts+"==="+cc+"==="+feedDevice[cc]+"==="+feedStatus[cc]);

                    Message msg = new Message();
                    String ntype = PageS.feedType.get(feedDevice[cc]);

                    Log.e("refreshallui===3", counts+"==="+cc+"==="+ntype+"==="+feedDevice[cc]+"==="+feedStatus[cc]);

                    msg.what = Integer.parseInt(ntype);
                    Bundle bundle = new Bundle();
                    bundle.putString("feedDevice", feedDevice[cc]);
                    bundle.putString("feedStatus", feedStatus[cc]);
                    msg.setData(bundle);

                    Log.e("refreshallui===4", counts+"==="+cc+"==="+ntype+"==="+feedDevice[cc]+"==="+feedStatus[cc]+"==="+feedOK(feedDevice[cc]));

                    if (feedOK(feedDevice[cc])) {
                        PageS.feedMap.put(feedDevice[cc], feedStatus[cc]);
                    }
                    mHandler.sendMessage(msg);
                }
            }
        }
    }

    public boolean feedOK(String entr) {
        String[] tmpAll = new String[]{"0071", "0072", "0073", "0074", "0075", "0076", "0081", "0082", "0099", "0099", "0099", "0086", "0087", "1010", "1011", "71b0", "72b0", "73b0"};
        return TransformUtils.isAvail(tmpAll, entr);
    }

    @SuppressLint("HandlerLeak")
    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {//串口接收数据 或者  mHandler.sendMessage(msg);
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Toast mToast = Toast.makeText(MainActivityf.this, "请检查网络设置", Toast.LENGTH_SHORT);
                    mToast.show();
                    break;
                case 1://开关反馈
                    // int myPosition = TransformUtils.findPosition(PageS.feedDArray, myDevice);
                    // if (myPosition != -1) {
                    String myDevice = msg.getData().getString("feedDevice");
                    String myStatus = msg.getData().getString("feedStatus");
                    int picId =feedPicID.get(myDevice);
                    int icoId =feedIconID.get(myDevice);
                    if( (picId != -1)&&(icoId != -1)){
                        boolean fstt = myStatus.equals("0001") ? true:false;
                        newm.touchFlag=false;
                        testFeed(picId,icoId,fstt);
                        Log.e("feegTag","myposition");
                    }
                    break;
                case 2://在收到消息时，电压显示界面
                    String myDevicex = msg.getData().getString("feedDevice");
                    String myStatusx = msg.getData().getString("feedStatus");
                    disv(myDevicex,myStatusx);
                    break;
                case 3://界面切换
                    String[] src = {"0","1","2","3","4","5","6","7","8","9","10","11"};
                    //通过 Bundle传过来
                    String myjmpposition = msg.getData().getString("jmppageno");
                    jmpPostion = Integer.parseInt(myjmpposition);
                    if ((currentPage!=jmpPostion)&&(TransformUtils.IsInArray(src,jmpPostion + ""))) {
                        refreshui(jmpPostion);
                    }
                    break;
                case 4://在收到消息时，对界面进行更新
                    String myStatusa = "0001";
                    String myjmppositionx = msg.getData().getString("jmppageno");
                    int jmpPostionx = Integer.parseInt(myjmppositionx);
                    if (jmpPostionx!= -1) {
                        myStatusa = PageS.feedMap.get(PageS.feedDArray[jmpPostionx]);
                        boolean fstt = myStatusa.equals("0001") ? false:true;
                        //testFeed(jmpPostionx,fstt);
                        Log.e("feegTag4", myStatusa);
                    }
                    break;
                case 5://在收到消息时，对界面进行更新
                    String myStatusay = "0000";
                    String myjmppositionxy = msg.getData().getString("jmppageno");
                    int jmpPostionxy = Integer.parseInt(myjmppositionxy);
                    if (jmpPostionxy!= -1) {
                        myStatusay = PageS.feedMap.get(PageS.feedDArray[jmpPostionxy]);
                        boolean fstt = myStatusay.equals("0001") ? true:false;
                        // testFeed(jmpPostionxy,fstt);
                        Log.e("feegTag5",myStatusay);

                    }
                    break;
                case 6://在收到消息时，对界面进行更新
                    String myDevicex6 = msg.getData().getString("feedDevice");
                    String myStatusx6 = msg.getData().getString("feedStatus");
                    dish(myDevicex6,myStatusx6);
                    break;
                default:
                    break;
            }
        }
    };

     private class AsyncTaskRunner extends AsyncTask<Void,  String, Void> {
        private String resp;
        LocalServerSocket serverSocket;
        @Override
        protected Void doInBackground(Void... params) {
            try {
                            //socketAddress需跟localSocket地址一致，否则无法连接上
                            serverSocket = new LocalServerSocket(SOCKET_ADDRESS);
                            BufferedReader reader;
                            String message;
                            String line = "";
                            while (true) {
                                LocalSocket accept = serverSocket.accept();
                                InputStream ips = accept.getInputStream();
                                ByteArrayOutputStream byteOps = new ByteArrayOutputStream();
                                byte[] buf = new byte[1024];
                                int len = -1;
                                while((len = ips.read(buf)) != -1){
                                    byteOps.write(buf, 0, len);
                                }
                                byte[] array = byteOps.toByteArray();
                                String msg = new String(array);
                                ips.close();
                                accept.close();
                               publishProgress(msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            testView.setText("finished");
        }
        @Override
        protected void onPreExecute() {
            resp = "TransformUtils.comingdata";
        }
        @Override
        protected void onProgressUpdate(String... values) {
                   testView.setText(values[0]);
         }
    }

    public void creatBitmap1() {
        try {
            //创建File
            bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.a2);
            int strId = getResources().getIdentifier("a1", "drawable", getPackageName());
            // strId = getResources().getIdentifier("a1", "drawable", "android");
            //  int id_up =getResourceByReflect("a1");
            String str = getResourcesUri(strId);//new File("/res/drawable/a2.PNG");
            URI uri = URI.create(str);
            File file = new File(new URI(uri.toString()));
            //文件输出流
            OutputStream os = new FileOutputStream(file);
            //把drawable的picture图片转换为位图
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.a1);
            //把picture位图复制一份到sdcard的file位置
            bitmap.compress(Bitmap.CompressFormat.PNG, 50, os);
            PageS.bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.a2);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}